package com.wsjc.web.controller.login;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wsjc.common.core.entity.ApiCommonResultVo;
import com.wsjc.web.controller.cache.LogOutChace;
import com.wsjc.web.controller.cache.TgTCache;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

/**
 * Created by dujinkai on 2018/5/29.
 * 登录控制器
 */
@Controller
public class WjSsoLogoutController {

	private static Logger logger = LoggerFactory.getLogger(WjSsoLogoutController.class);
	
    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public ApiCommonResultVo logout(HttpServletRequest request) {
        // 销毁tgc
    	String tgc = getTgcFromCokie(request);
    	if(StringUtils.isEmpty(tgc)){
    		return new ApiCommonResultVo(-1, "tgc is null", "");
    	}
        TgTCache.getInstance().removeTgt(tgc);

        Map<String, String> map = LogOutChace.getInstance().getAll();

        map.forEach((key, value) -> subSystemLogOut(value, key));

        LogOutChace.getInstance().removeAll();

        return new ApiCommonResultVo(0, "success", "");
    }

    /**
     * 各个子系统退出登录
     */
    private void subSystemLogOut(String logOutUrl, String sessionId) {

        try {
            URL url = new URL(logOutUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
            connection.setDoInput(true);

            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            if(StringUtils.isEmpty(sb.toString()) && sb.toString().equals("SUCCESS")){
            	logger.info("SSO-server|logout success...: " + logOutUrl);
            	return;
            }
            logger.info("SSO-SERVER|logout fail...: " + logOutUrl);
            
        } catch (Exception e) {
        	logger.error("SSO-SERVER|ERROR|error info : ", e);
        }
    }




    /**
     * 从cookie中获得tgc
     * @return 返回tgc
     */
    private String getTgcFromCokie(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();
        // 没有cookie直接返回空
        if (null == cookies) {
            return "";
        }
        // tgc的cookie
        Optional<Cookie> tgcCookie = Arrays.stream(cookies).filter(cookie -> "TGC".equals(cookie.getName())).findFirst();

        // 存在tgc 的cookie
        if (tgcCookie.isPresent()) {
            return tgcCookie.get().getValue();
        }
        return "";
    }
}
